package com.richard.main

import android.content.Context
import android.os.Process
import com.richard.base.BaseApplication
import com.richard.base.common.activityManager
import com.richard.base.common.isMainProcess
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.KoinContextHandler
import org.koin.core.context.loadKoinModules
import org.koin.core.context.startKoin


/**
 ***************************************
 * 项目名称:kaishuvideo
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2019/12/18     7:04 PM
 * 用途 主application
 ***************************************
 *
 */
//@AppSpec
open class MainApp : BaseApplication() {

    override fun onCreate() {

        super.onCreate()
        if (isMainProcess()) {
            // Start Koin
//            loadKoinModules(mainModule)
        }

    }


    override fun attachBaseContext(base: Context?) {
        if (base?.packageName == getProcessName(base)) {
            val koin = KoinContextHandler.getOrNull()
            if (koin == null) {
                startKoin {
                    androidLogger()
                    androidContext(base ?: this@MainApp)
                }
            }
        }
        super.attachBaseContext(base)
    }


    /**
     * 为了方便在 attachBaseContext 方法里面用，暂时先写在这儿，把问题解决了 再移动到其他地方。
     * @param context Context?
     * @return String?
     */
    fun getProcessName(context: Context?): String? {
        try {
            val runningApps = context?.activityManager?.runningAppProcesses ?: return null
            for (proInfo in runningApps) {
                if (proInfo.pid == Process.myPid()) {
                    if (proInfo.processName != null) {
                        return proInfo.processName
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

}